package com.my.httpapi.api.baseView;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;

import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.android.arouter.launcher.ARouter;
import com.my.httpapi.R;
import com.my.httpapi.api.aspect.ViewInjectUtils;
import com.my.httpapi.api.baseApi.ComObserver;
import com.my.httpapi.api.baseApi.ComTransformer;
import com.my.httpapi.api.baseApi.ComTransformerNoCode;
import com.my.httpapi.api.baseApiInterface.OnLoadingListener;
import com.my.httpapi.api.baseApiInterface.ProgressManageError;
import com.my.httpapi.api.baseMyView.LoadingView;
import com.my.httpapi.api.baseUtils.ActivityStackHelper;
import com.my.httpapi.api.baseUtils.BaseUtils;
import com.my.httpapi.api.baseUtils.HApi;
import com.my.httpapi.api.baseUtils.RequestParameter;
import com.my.httpapi.api.baseUtils.Toast;

import java.io.Serializable;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;
import okhttp3.RequestBody;

/**
 * Author:guohaijin
 * Date:
 * Description:
 */
public abstract class BaseActivity extends AppCompatActivity {
    private FrameLayout mContentContainer;//内容 容器
    private FrameLayout mContentContainertitle;//title 容器
    private boolean isShouwTitle = false;//是否显示title
    private TextView textTitle;//title 中间文字控件
    private String titleStr;//title 中间文字
    private LinearLayout ll_btn_left;//返回箭
    private TextView rl_title_rightname;//title 右边文字控件
    private ImageView ivLogo;
    private RelativeLayout rl_title;
    private ImageView iv_left_icon;
    private CompositeDisposable mCompositeDisposable;
    private AlertDialog pd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (statusBarIsBlack()) {
            BaseUtils.setImmersiveStatusBarColorBlack(this);
        } else {
            BaseUtils.setImmersiveStatusBar(this);
        }
        initView(this);
        String s = showTitle();
        isShowTitle(s);
        setContentView(ViewInjectUtils.injectLayout(this));
        ActivityStackHelper.add(this);
        if (showLeftArrow()) {
            isShowTitleLeft(View.VISIBLE);
        } else {
            isShowTitleLeft(View.GONE);
        }
        initView();
        initData(savedInstanceState);
    }

    protected abstract void initView();

    protected abstract void initData(Bundle savedInstanceState);

    protected abstract void destory();

    protected abstract String showTitle();

    protected abstract boolean statusBarIsBlack();

    protected abstract boolean showLeftArrow();

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityStackHelper.remove(this);
        if (mCompositeDisposable != null) {
            mCompositeDisposable.clear();
            mCompositeDisposable = null;
        }
        destory();
    }

    private void initView(Context context) {
        ARouter.getInstance().inject(this);
        if (mCompositeDisposable == null) mCompositeDisposable = new CompositeDisposable();

        LinearLayout root = new LinearLayout(context);
        root.setOrientation(LinearLayout.VERTICAL);
        super.setContentView(root);

        LinearLayout.LayoutParams paramTitle = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mContentContainertitle = new FrameLayout(context);
        root.addView(mContentContainertitle, paramTitle);

        LinearLayout.LayoutParams paramContent = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, 0);
        paramContent.weight = 1;
        mContentContainer = new FrameLayout(context);
        root.addView(mContentContainer, paramContent);
    }

    @Override
    public void setContentView(int layoutResID) {
        if (isShouwTitle) {
            View viewtTitle = LayoutInflater.from(this).inflate(getTitleLayoutId(), mContentContainertitle);
            init(viewtTitle);
        }
        LayoutInflater.from(this).inflate(layoutResID, mContentContainer);
    }

    @Override
    public void setContentView(View view) {
        FrameLayout.LayoutParams paramtitle = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mContentContainertitle.addView(view, paramtitle);

        FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mContentContainer.addView(view, param);
    }

    public int getTitleLayoutId() {
        return R.layout.title_bar;
    }

    @SuppressLint("ResourceType")
    private void init(View view) {
        ll_btn_left = view.findViewById(R.id.ll_btn_left);
        rl_title = view.findViewById(R.id.rl_title);
        textTitle = view.findViewById(R.id.tv_title);
        rl_title_rightname = view.findViewById(R.id.tv_right_txt);
        ivLogo = view.findViewById(R.id.iv_right_icon);
        iv_left_icon = view.findViewById(R.id.iv_left_icon);
        if (!TextUtils.isEmpty(titleStr))
            textTitle.setText(titleStr);
        ll_btn_left.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }
        });
        rl_title_rightname.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                titleRightOnclick();
            }
        });
        ivLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                titleRightOnclick();
            }
        });
//        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) rl_title.getLayoutParams();
//        params.height = ScreenUtils.getScreenHeight(this)/10;
//        rl_title.setLayoutParams(params);
        if(HApi.vrightColor!=-1){
            rl_title_rightname.setTextColor(getResources().getColor(HApi.vrightColor));
        }
        if(HApi.vtitleBg!=-1) {
            rl_title.setBackgroundColor(getResources().getColor(getResources().getColor(HApi.vtitleBg)));
        }
        if(HApi.vtitleColor!=-1) {
            textTitle.setTextColor(getResources().getColor(HApi.vtitleColor));
        }
    }

    protected RequestBody getParams(Map<String, Object> map) {
        return RequestParameter.generate().getParams(map).create();
    }

    private void isShowTitle(boolean isShouwTitle) {
        this.isShouwTitle = isShouwTitle;
    }

    private void isShowTitle(String text) {
        if (TextUtils.isEmpty(text)) {
            this.isShouwTitle = false;
        } else {
            this.isShouwTitle = true;
            this.titleStr = text;
        }
    }

    @SuppressLint("ResourceType")
    public void setBg(@IdRes int color, @IdRes int txtColor, int txtSize) {
        if (rl_title != null) {
            rl_title.setBackgroundColor(getResources().getColor(color));
        }
        if (textTitle != null) {
            textTitle.setTextColor(getResources().getColor(txtColor));
        }

        if (textTitle != null) {
            textTitle.setTextColor(getResources().getColor(txtColor));
            textTitle.setTextSize(TypedValue.COMPLEX_UNIT_SP, txtSize);
        }
    }

    @SuppressLint("ResourceType")
    public void setRightTextColor(@IdRes int txtColor) {
        if (rl_title_rightname != null) {
            rl_title_rightname.setTextColor(getResources().getColor(txtColor));
        }
    }

    public void setRightTextSize(int txtSize) {
        if (rl_title_rightname != null) {
            rl_title_rightname.setTextSize(TypedValue.COMPLEX_UNIT_SP, txtSize);
        }
    }


    @SuppressLint("ResourceType")
    public void setleftArrowIcon(@IdRes int res) {
        if (iv_left_icon != null) {
            iv_left_icon.setImageResource(res);
        }
    }

    public void setTitle(String text) {
        if (!TextUtils.isEmpty(text)) {
            textTitle.setText(text);
            rl_title.setVisibility(View.VISIBLE);
        } else {
            rl_title.setVisibility(View.GONE);
        }
    }

    public void setTitleTextRight(String text) {
        if (rl_title_rightname != null) {
            rl_title_rightname.setVisibility(View.VISIBLE);
            rl_title_rightname.setText(text);
        }
    }

    public void setTitleIconRight(int logo) {
        if (ivLogo != null) {
            ivLogo.setVisibility(View.VISIBLE);
            ivLogo.setBackgroundResource(logo);
        }
    }

    public ImageView getRightIconView() {
        return ivLogo;
    }

    public void isShowTitleLeft(int isShow) {
        if (ll_btn_left != null)
            ll_btn_left.setVisibility(isShow);
    }

    public void titleRightOnclick() {
    }//给子类复写


    protected void intent(Class activity) {
        Intent intent = new Intent(getApplicationContext(), activity);
        startActivity(intent);
    }

    protected void intentFinish(Class activity) {
        Intent intent = new Intent(getApplicationContext(), activity);
        startActivity(intent);
        finish();
    }

    protected void intent(Class activity, int classType) {
        Intent intent = new Intent(getApplicationContext(), activity);
        startActivityForResult(intent, classType);
    }

    protected void intent(Class activity, Map<String, Object> map) {
        intent(activity, -100, map);
    }

    protected void intent(Class activity, int classType, Map<String, Object> map) {
        Intent intent = new Intent(getApplicationContext(), activity);
        for (String key : map.keySet()) {
            if (map.get(key) instanceof Integer) {
                intent.putExtra(key, ((Integer) map.get(key)).intValue());
            } else if (map.get(key) instanceof String) {
                intent.putExtra(key, map.get(key).toString());
            } else if (map.get(key) instanceof Float) {
                intent.putExtra(key, ((Float) map.get(key)).floatValue());
            } else if (map.get(key) instanceof Double) {
                intent.putExtra(key, ((Double) map.get(key)).doubleValue());
            } else if (map.get(key) instanceof Serializable) {
                intent.putExtra(key, ((Serializable) map.get(key)));
            }
        }
        if (classType == -100) {
            startActivity(intent);
        } else {
            startActivityForResult(intent, classType);
        }
    }

    protected void initProgressDialog() {
        if (pd == null) {
            pd = new LoadingView(this, com.my.httpapi.R.style.AlertDialog, true);
            pd.setCancelable(true);
        }
    }

    protected void progressDialogShow() {
        if (pd != null && !pd.isShowing()) {
            pd.show();
        }
    }

    protected void progressDialogDismiss() {
        if (pd != null) {
            pd.dismiss();
            pd = null;
        }
    }

    protected void copyStr(String text) {
        //获取剪贴版
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        //创建ClipData对象
        //第一个参数只是一个标记，随便传入。
        //第二个参数是要复制到剪贴版的内容
        ClipData clip = ClipData.newPlainText("copy", text);
        //传入clipdata对象.
        clipboard.setPrimaryClip(clip);
        Toast.show("复制成功");
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }


    protected void subscribe(Observable observable, ComObserver comObserver) {
        observable.compose(new ComTransformer()).subscribe(comObserver);
    }

    protected void subscribeNoCode(Observable observable, ComObserver comObserver) {
        observable.compose(new ComTransformerNoCode()).subscribe(comObserver);
    }


    /**
     * @显示默认loading的请求
     */
    protected ComObserver request(OnLoadingListener onLoadingListener) {
        return request(onLoadingListener, true);
    }

    /**
     * @自定义是否显示loading的请求
     */
    protected ComObserver request(OnLoadingListener onLoadingListener, boolean isLoading) {
        return new ComObserver(mCompositeDisposable, onLoadingListener, this, isLoading);
    }

    /**
     * @自定义loading样式的请求
     */
    protected ComObserver request(OnLoadingListener onLoadingListener, AlertDialog alertDialog) {
        return new ComObserver(mCompositeDisposable, onLoadingListener, alertDialog, this, true);
    }

    /**
     * @显示默认loading的请求并且请求带错误回调
     */
    protected ComObserver request(OnLoadingListener onLoadingListener, ProgressManageError progressManageError) {
        return request(onLoadingListener, progressManageError, true);
    }

    /**
     * @自定义是否显示loading的请求并且请求带错误回调
     */
    protected ComObserver request(OnLoadingListener onLoadingListener, ProgressManageError progressManageError, boolean isLoading) {
        return new ComObserver(mCompositeDisposable, onLoadingListener, progressManageError, this, isLoading);
    }

    /**
     * @自定义loading样式的请求并且请求带错误回调
     */
    protected ComObserver request(OnLoadingListener onLoadingListener, AlertDialog alertDialog, ProgressManageError progressManageError) {
        return new ComObserver(mCompositeDisposable, onLoadingListener, alertDialog, progressManageError, this, true);
    }
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (ev.getAction() == MotionEvent.ACTION_DOWN){
//            // 判断连续点击事件时间差
//            if (TimeUtils.isFastClick()){
//                return true;
//            }
//        }
//        return super.dispatchTouchEvent(ev);
//    }
}
